package com.wanyu.video.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

    public static void main(String[] args) {



        // 创建Boss Group 和 Worker Group。 BossGroup 用来处理连接请求，WorkerGroup用来处理业务请求
        // 默认group下创造的线程个数是cpu * 2,
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {

            // 创建服务端的启动对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // 使用NioServerSocketChannel作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true) // 设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerSimpleHandler());
                        }
                    }); // 给worker Group 设置处理器(Handler)

            System.out.println("服务器 is ready");

            // 启动服务器并绑定端口
            ChannelFuture cf = bootstrap.bind(6668).sync();

            cf.addListener((ChannelFutureListener) future -> {
                if (cf.isSuccess()){
                    System.out.println("监听端口 6668 成功");
                }else {
                    System.out.println("监听端口 6668 失败");
                }
            });
            // 对关闭通道进行监听
            cf.channel().closeFuture().sync();
        }catch (Exception e){
           e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}
